package model;

import serverMessage.ServerMessage;
import database.DbFile;
import database.User;

/**
 * class AddFileRequest - for adding a file
 */
public class AddFileRequest extends Request {
	String userID;
	String fileName;
	String filePath;
	byte[] byteFile;
	long checksum;
	boolean isMyDropBox;
	boolean isWebUpload;
	
	/**
	 * constructor
	 * @param userID - the user name
	 * @param fileName - the file name
	 * @param filePath - the file path
	 * @param byteFile - the file content as an array of bytes
	 * @param checksum - id of the file content (hash)
	 * @param isMyDropBox - false if the file is not directly under the dropbox root, true else
	 */
	public AddFileRequest(String userID,String fileName,String filePath,byte[] byteFile,long checksum, boolean isMyDropBox, boolean isWebUpload)
	{
		super();
		this.userID = userID;
		this.fileName = fileName;
		this.filePath = filePath;
		this.byteFile = byteFile;
		this.checksum = checksum;
		this.isMyDropBox = isMyDropBox;
		this.isWebUpload = isWebUpload;
	}
	
	@Override
	/**
	 * add the user's file 
	 */
	public Integer call() {
		// TODO Auto-generated method stub
				
		Integer folderID;
		
		//get the folder id that the file is under it
		if (!isMyDropBox)
		{
			//get the folder name	
			String withoutFile = filePath.substring(0, filePath.lastIndexOf("\\"));
			String folderName = withoutFile.substring(withoutFile.lastIndexOf("\\")+1);
			folderID = DbAdapter.getInstance().getDbFolderID(userID, folderName);
		}
		else
		{
			folderID = DbAdapter.getInstance().getUserDropboxFolderID(userID);
		}
		
		//if he don't have such folder
		if (folderID==-1)
		{
			System.out.println("user don't have this folder");
			return 0;
		}
		
		DbFile file = new DbFile(folderID,checksum,fileName);
		
		System.out.println("add file..");
		
		//create the file at ".\files" at server side
		convByteToFile(byteFile,String.valueOf(checksum)+fileName.substring(fileName.lastIndexOf(".")));
		
		//add the file to the DB and update users that shared with him the folder
		if (DbAdapter.getInstance().addDbFile(file)!=0)
		{
			ServerMessage message = new ServerMessage(userID, "create_file", folderID.toString() , fileName, byteFile);
			UsersMessages.getInstance().addMessage(DbAdapter.getInstance().usersSharedFolder(userID, folderID), message);
			
			//if the file come from the web - need to tell to the user to add it too
			if (isWebUpload)
			{
				//if the file is directly under the dropbox
				if (isMyDropBox)
					message = new ServerMessage(userID, "create_file_in_dropbox", folderID.toString() , fileName, byteFile);
				
				UsersMessages.getInstance().addMessage(userID,message);
				
			}
				
			
			return 1;
		}
		
		return 0;
	}


}
